from flask import Blueprint, request, jsonify
from tools.myjwt import JWTManager
from tools.myredis import redis_manager
import re

user_blue = Blueprint('user', __name__)

@user_blue.route('/login', methods=['POST'])
def login():
    """
    用户登录接口
    
    请求参数:
        username (str): 用户名
        password (str): 密码
    """
    try:
        # 1. 获取POST数据
        data = request.get_json()
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据不能为空"
            }), 400
        
        username = data.get('username')
        password = data.get('password')
        
        # 2. 数据验证
        if not username or not password:
            return jsonify({
                "code": 400,
                "message": "用户名和密码不能为空"
            }), 400
        
        # 简单的用户名格式验证
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
            return jsonify({
                "code": 400,
                "message": "用户名格式不正确，应为3-20位字母、数字或下划线"
            }), 400
        
        # 简单的密码长度验证
        if len(password) < 6:
            return jsonify({
                "code": 400,
                "message": "密码长度不能少于6位"
            }), 400
        
        # 3. 模拟用户验证（实际项目中应该查询数据库）
        if username == 'admin' and password == '123456':
            # 4. 生成JWT令牌
            user_id = 1
            access_token = JWTManager.generate_access_token(user_id, username)
            refresh_token = JWTManager.generate_refresh_token(user_id, username)
            
            # 5. 将refresh_token存储到Redis中
            redis_manager.store_refresh_token(user_id, refresh_token, 3600)  # 1小时过期
            
            # 6. 返回登录成功响应
            return jsonify({
                "code": 200,
                "message": "登录成功",
                "data": {
                    "access_token": access_token,
                    "refresh_token": refresh_token,
                    "token_type": "Bearer",
                    "expires_in": 1800,  # 30分钟，单位：秒
                    "user_info": {
                        "user_id": user_id,
                        "username": username
                    }
                }
            }), 200
        else:
            return jsonify({
                "code": 401,
                "message": "用户名或密码错误"
            }), 401
            
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"服务器内部错误: {str(e)}"
        }), 500

@user_blue.route('/logout', methods=['POST'])
def logout():
    """
    用户退出登录接口
    
    请求参数:
        access_token (str): 访问令牌
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据不能为空"
            }), 400
        
        access_token = data.get('access_token')
        if not access_token:
            return jsonify({
                "code": 400,
                "message": "缺少访问令牌"
            }), 400
        
        payload = JWTManager.decode_token(access_token)
        if 'error' in payload:
            return jsonify({
                "code": 401,
                "message": payload['error']
            }), 401
        
        user_id = payload.get('user_id')
        
        redis_manager.add_token_to_blacklist(access_token, 1800)
        redis_manager.delete_refresh_token(user_id)
        
        return jsonify({
            "code": 200,
            "message": "退出登录成功"
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"服务器内部错误: {str(e)}"
        }), 500

@user_blue.route('/refresh', methods=['POST'])
def refresh_token():
    """
    刷新token接口
    
    请求参数:
        refresh_token (str): 刷新令牌
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据不能为空"
            }), 400
        
        refresh_token = data.get('refresh_token')
        if not refresh_token:
            return jsonify({
                "code": 400,
                "message": "缺少刷新令牌"
            }), 400
        
        payload = JWTManager.decode_token(refresh_token)
        if 'error' in payload:
            return jsonify({
                "code": 401,
                "message": payload['error']
            }), 401
        
        if payload.get('token_type') != 'refresh':
            return jsonify({
                "code": 401,
                "message": "令牌类型错误"
            }), 401
        
        user_id = payload.get('user_id')
        username = payload.get('username')
        
        stored_refresh_token = redis_manager.get_refresh_token(user_id)
        if not stored_refresh_token or stored_refresh_token != refresh_token:
            return jsonify({
                "code": 401,
                "message": "刷新令牌无效或已使用"
            }), 401
        
        new_access_token = JWTManager.generate_access_token(user_id, username)
        new_refresh_token = JWTManager.generate_refresh_token(user_id, username)
        
        redis_manager.store_refresh_token(user_id, new_refresh_token, 3600)
        redis_manager.add_token_to_blacklist(refresh_token, 3600)
        
        return jsonify({
            "code": 200,
            "message": "令牌刷新成功",
            "data": {
                "access_token": new_access_token,
                "refresh_token": new_refresh_token,
                "token_type": "Bearer",
                "expires_in": 1800,
                "user_info": {
                    "user_id": user_id,
                    "username": username
                }
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"服务器内部错误: {str(e)}"
        }), 500

@user_blue.route('/userinfo', methods=['GET'])
def userinfo():
    """
    获取用户信息接口
    """
    try:
        user_info = request.current_user
        return jsonify({
            "code": 200,
            "message": "获取用户信息成功",
            "data": {
                "user_id": user_info.get('user_id'),
                "username": user_info.get('username'),
                "login_time": user_info.get('login_time')
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"服务器内部错误: {str(e)}"
        }), 500
